#include<stdio.h>
#include<stdlib.h>

struct topoNode
{
    char name[20];
    int parent[10];
    int cntPaS;
    int cntInRun;
};

int compare(int* s,int d,int len)
{
    int i;
    for(i=0;i<len;i++)
    {
        if(*s++ == d)
        {
            return 1;
        }
    }
    return 0;
}

void topo(struct topoNode* S,int length)
{
    int level=1;
    int numComplete=0;
    int* dirty=(int*)malloc(sizeof(int)*(length+1));
    memset(dirty,0,sizeof(int)*(length+1));//纪录被引用数变为0是否是新事件

    while(numComplete<length)
    {
        int i,j;
        for(i=1;i<=length;i++)
        {
            if(S[i].cntInRun==0 && dirty[i]==0)
            {
                printf("%d,%s\n",level,S[i].name);
                numComplete++;
                S[i].cntInRun=-1;//标志位：该元素已经被处理

                for(j=1;j<=length;j++)
                {
                    if(S[j].cntInRun>0 && compare(S[j].parent,i,S[j].cntPaS))
                    {
                        if(--S[j].cntInRun==0)
                        {
                            dirty[j]=1;
                        }
                    }
                }
            }
        }
        level++;
        memset(dirty,0,sizeof(int)*(length+1));
    }
}

int main()
{
    struct topoNode A[50];
    int nodeNum=0;//计数有多少个节点

    FILE* file;
    char* curLine;

    if((file=fopen("./topo.txt","r"))==NULL)
    {
        printf("File could not be opened.\n");
        exit(0);
    }

    int index,indexArrayNode;
    char lineName[30],*temp,indexP[10];
    while(fgets(lineName,1000,file)!=NULL)
    {

        nodeNum++;

        index=atoi(strtok(lineName,"\t"));
        A[index].cntPaS=0;

        strcpy(A[index].name,strtok(NULL,"\t"));

        while((temp=strtok(NULL,"\t")))
        {
            if(*temp!='\n' && *temp!=' ')
            {

                //printf("%s*****",temp);
                indexArrayNode=A[index].cntPaS++;
                A[index].parent[indexArrayNode]=atoi(temp);
                //printf("%d;",A[index].parent[indexArrayNode]);
            }

        }

        A[index].cntInRun=A[index].cntPaS;
    }
    topo(A,nodeNum);
}

